package cn.study.jmm;

import java.util.concurrent.CountDownLatch;

/**
 * @Author     ：跟大佳一起学架构
 * @Description：并发累加
 */
public class JmmAdd {
    // 保证两个线程并发
    private static CountDownLatch begin = new CountDownLatch(2);

    // 初始值
    int i = 5;

    // 线程1 累加3
    public void thread1Add() {
        begin.countDown();
        i = i + 3;
    }

    // 线程2 累加2
    public void thread2Add() {
        begin.countDown();
        i = i + 2;
    }

    /**
     * @description: 7 8 10
     * @param args
     * @return void
     */
    public static void main(String[] args) throws InterruptedException {
        JmmAdd test = new JmmAdd();
        // 启动两个线程  执行1000次看下效果
        for (int i = 0; i < 1000; i++) {
            Thread threadA = new Thread(() -> test.thread1Add(), "threadA");
            threadA.start();
            Thread threadB = new Thread(() -> test.thread2Add(), "threadB");
            threadB.start();
            begin.await();
            System.out.println(test.getI());
            test.setI(5);
        }
    }

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }
}
